#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
清空文件夹

闲云潭影日悠悠, 物转星移几度秋!
						--王勃
"""

import os
import shutil

def clear_tree(tar_dir):
	''' Python3 清空文件夹 '''

	for root, dirs, files in os.walk(tar_dir):
		for tree in dirs:
			tree = os.path.join(root, tree)
			try:
				shutil.rmtree(tree)
				print('删除临时文件夹 {tree} 成功'.format(tree=tree))
			except WindowsError as e:
				print(e)
		for file in files:
			file = os.path.join(root, file)
			try:
				os.remove(file)
				print('删除临时文件 {file} 成功'.format(file=file))
			except WindowsError as e:
				print(e)
				

def getFileInfo(dirPath):
	for root, dirs, files in os.walk(dirPath):
		fileInfo = {
			'path': root,
			'dirs': dirs,
			'files': files,
			}
		return fileInfo
	else:
		return {}

# path = os.environ.get('TEMP')

# print getFileInfo(path)

def toGBK(text):
	print unicode(text, 'utf-8').encode('gbk')

def returnGBK(text):
	return unicode(text, 'utf-8').encode('gbk')

def returnUTF8(text):
	try:
		return unicode(text, 'gbk').encode('utf-8')
	except:
		return text

def delFile(path):
	"""删除文件"""
	if os.path.isfile(path):
		try:
			os.remove(path)
			toGBK("删除文件成功√ %s ..." % returnUTF8(path))
			# toGBK("删除文件成功√...")
		except Exception as e:
			# toGBK("删除文件失败√...")
			toGBK("删除文件失败× %s ..." % returnUTF8(path))
	else:
		try:
			shutil.rmtree(path)
			os.mkdir(path) 
			# toGBK("清空文件夹成功√  ...")
			toGBK("清空文件夹成功√ %s ..." % returnUTF8(path))
		except Exception as e:
			# toGBK("清空文件夹失败× ..." )
			toGBK("清空文件夹失败× %s ..." % returnUTF8(path))

def clearFile(path):
	'''

	清空文件夹
	'''
	fileInfo = getFileInfo(path)
	if fileInfo:
		dirPath = fileInfo['path']

		files = fileInfo['dirs'] + fileInfo['files']

		for file in files:
			file = dirPath + '\\' + file
			delFile(file)

def main(path):
	raw_input(returnGBK("开始清空windows系统, 临时文件夹, 回车开始..."))
	clearFile(path)
	raw_input(returnGBK("清空windows系统, 临时文件夹结束, 回车退出.."))



if __name__ == '__main__':
	path = os.environ.get('TEMP')
	main(path)